package com.pac.doctor.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.common.page.Page;
import com.common.page.PageContext;
import com.common.tools.StringTools;
import com.common.tools.TimeTools;
import com.common.util.LogicException;
import com.common.util.PropertyUtils;
import com.common.util.SessionKeyContent;
import com.pac.doctor.bean.DoctorBean;
import com.pac.doctor.service.DoctorService;
import com.pac.file.bean.FileBean;
import com.pac.file.service.FileService;
import com.pac.role.RoleKeyContent;
import com.pac.user.UserKeyContent;
import com.pac.user.bean.UserBean;
import com.pac.user.service.UserService;

/***
 * 
 * 医生bean控制层 <功能详细描述>
 * 
 * @author zhang jing
 * @version [版本号, 2015年3月15日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Controller
@Scope("prototype")
@RequestMapping("/doctor")
public class DcotorController {

	private static Logger logger = Logger.getLogger(DcotorController.class);

	@Autowired
	private DoctorService doctorService;

	@Autowired
	private FileService fileService;

	@Autowired
	private UserService userService;

	/****
	 * 列表查询
	 * 
	 * @param request
	 * @param doctorBean
	 * @param page
	 * @param rows
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/listData")
	@ResponseBody
	public Page queryUserList(HttpServletRequest request,
			DoctorBean doctorBean, int page, int rows) {
		// 设置每页记录数
		PageContext.getContext().setPageSize(rows);
		// 跳转到指定页
		PageContext.getContext().gotoPage(page);

		// 超级管理员可以看到所有医生，医院管理员只能看到自己所管医院的医生
		HttpSession session = request.getSession();
		UserBean userBeans = (UserBean) session
				.getAttribute(SessionKeyContent.SESSION_KEY_OBJ_USER_BEAN);
		if (!UserKeyContent.USER_ID_SYSTEM.equals(userBeans.getId())) {
			doctorBean.setManagerUserId(userBeans.getId());
		}

		List<DoctorBean> list = doctorService.queryDoctor(doctorBean);

		Page currentPage = new Page();
		// 总行数
		int totlaRols = PageContext.getContext().getTotal();
		currentPage.setTotal(totlaRols);
		currentPage.setRows(list);

		return currentPage;
	}

	/**
	 * 添加用户
	 * 
	 * @param userBean
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/save")
	@ResponseBody
	public Map<String, Object> addUser(DoctorBean doctorBean,
			UserBean userBean, MultipartFile imgUrl) {
		boolean result = true;
		String msg = "";
		if (imgUrl.getSize() > 0) {
			// 上传文件
			String filePath = TimeTools.now("yyyy") + "/" + TimeTools.now("MM")
					+ "/" + TimeTools.now("dd");
			String tempDir = PropertyUtils.getValue("file.temp.dir");
			tempDir += "/" + StringTools.randomCode(32) + ".tmp";
			File upFile = new File(tempDir);
			try {
				imgUrl.transferTo(upFile);
			} catch (IllegalStateException e1) {
				logger.error(e1);
			} catch (IOException e1) {
				logger.error(e1);
			}

			FileBean fileBean = fileService.uploadImg(upFile,
					imgUrl.getOriginalFilename(), filePath, true, 200, 266);

			String img_Url = fileBean.getPath();
			// 保存用户
			userBean.setNickname(doctorBean.getName());
			userBean.setCreateDate(TimeTools.now());
			userBean.setHeadImg(img_Url);
			userBean.setRoleIds(RoleKeyContent.ROLE_ID_DOCTOR);
			String userId = userService.addUser(userBean);
			try {
				doctorBean.setUserId(userId);
				doctorBean.setImg(img_Url);
				doctorBean.setCreateDate(TimeTools.now());
				doctorService.addDoctor(doctorBean);
				msg = "新增医生【" + doctorBean.getName() + "】成功";
			} catch (LogicException e) {
				result = false;
				msg = e.getMessage();
				logger.error("新增医生出错：" + e.getMessage());
			} catch (Exception e) {
				result = false;
				msg = "新增医生出错，系统内部错误";
				logger.error("新增医生出错：" + e);
			}
		} else {
			result = false;
			msg = "新增医生出错，头像不能为空";
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", result);
		map.put("msg", msg);
		return map;
	}

	/***
	 * 修改医院信息 <功能详细描述>
	 * 
	 * @param hospitalBean
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public Map<String, Object> edit(DoctorBean doctorBean, UserBean userBean,
			MultipartFile imgUrl) {
		boolean result = true;
		String msg = "";
		String img_Url = "";

		if (imgUrl.getSize() > 0) {
			// 上传文件
			String filePath = TimeTools.now("yyyy") + "/" + TimeTools.now("MM")
					+ "/" + TimeTools.now("dd");
			String tempDir = PropertyUtils.getValue("file.temp.dir");
			tempDir += "/" + StringTools.randomCode(32) + ".tmp";
			File upFile = new File(tempDir);
			try {
				imgUrl.transferTo(upFile);
			} catch (IllegalStateException e1) {
				logger.error(e1);
			} catch (IOException e1) {
				logger.error(e1);
			}
			FileBean fileBean = fileService.uploadFile(upFile,
					imgUrl.getOriginalFilename(), filePath);

			img_Url = fileBean.getPath();
		}

		// 修改用户信息
		userBean.setId(doctorBean.getUserId());
		List<UserBean> list = userService.queryUser(userBean);
		UserBean user = list.get(0);
		user.setUserName(userBean.getUserName());
		user.setPassword(userBean.getPassword());
		if (!img_Url.equals("")) {
			user.setHeadImg(img_Url);
			doctorBean.setImg(img_Url);
		}
		userService.editUserBase(user);

		// 保存修改的用户信息
		try {
			doctorService.updateDoctor(doctorBean);
			msg = "修改用户【" + doctorBean.getName() + "】成功";
		} catch (LogicException e) {
			result = false;
			msg = e.getMessage();
			logger.error("修改医生出错：" + e.getMessage());
		} catch (Exception e) {
			result = false;
			msg = "修改医生出错，系统内部错误";
			logger.error("修改医生出错：" + e);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", result);
		map.put("msg", msg);

		return map;
	}

	/***
	 * 删除 <功能详细描述>
	 * 
	 * @param id
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Map<String, Object> delete(DoctorBean doctorBean) {
		boolean result = true;
		String msg = "";
		try {
			this.doctorService.delDoctor(doctorBean);
			msg = "删除用户成功";
		} catch (LogicException e) {
			result = false;
			msg = e.getMessage();
		} catch (Exception e) {
			result = false;
			msg = "删除用户出错，系统内部错误";
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", result);
		map.put("msg", msg);

		return map;

	}

	/***
	 * 页面跳转 <功能详细描述>
	 * 
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("gotoPage")
	public ModelAndView gotoPage(String pageName) {
		ModelAndView mov = new ModelAndView();
		mov.setViewName("doctor/" + pageName);
		return mov;
	}
}
